package org.example.simpleboot.initializer;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * @author Administrator
 */
@HandlesTypes(WebApplicationInitializer.class)
public class MySpringServletContainerInitializer implements ServletContainerInitializer {
    @Override
    public void onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext) throws ServletException {
        List<WebApplicationInitializer> initializers = new LinkedList<>();
        if (webAppInitializerClasses != null) {
            for (Class<?> webAppInitializerClazz : webAppInitializerClasses) {
                if (!webAppInitializerClazz.isInterface() && !Modifier.isAbstract(webAppInitializerClazz.getModifiers()) &&
                        WebApplicationInitializer.class.isAssignableFrom(webAppInitializerClazz)) {
                    try {
                        initializers.add((WebApplicationInitializer) webAppInitializerClazz.newInstance());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        if (initializers.isEmpty()) {
            servletContext.log("sorry！没有WebApplicationInitializer的实例");
            return;
        }

        servletContext.log("WebApplicationInitializer实例数：" + initializers.size());
        for (WebApplicationInitializer initializer : initializers) {
            initializer.onStartup(servletContext);
        }
    }
}
